package com.wing.oauth2.extension.warehouse;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.wing.common.exception.BusinessException;
import com.wing.oauth2.details.userdetails.warehouse.WarehouseUserDetailsServiceImpl;
import com.wing.warehouse.feign.WarehouseUserClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.HashSet;
import java.util.Map;

/**
 * 微信认证提供者
 *
 * @author
 */
@Data
public class WarehouseAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;
    private WarehouseUserClient warehouseUserClient;

    @Autowired
    private WarehouseUserDetailsServiceImpl warehouseUserDetailsService;



    /**
     * 微信认证
     *
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WarehouseAuthenticationToken authenticationToken = (WarehouseAuthenticationToken) authentication;
        String code = (String) authenticationToken.getPrincipal();
        UserDetails userDetails = warehouseUserDetailsService.loadUserByUsername(code);
        Map details = (Map)authenticationToken.getDetails();
        String password = details.get("password").toString();
        boolean b = new BCryptPasswordEncoder().matches(password,userDetails.getPassword());
        if(!b){
            throw new BusinessException("密码错误");
        }
        WarehouseAuthenticationToken result = new WarehouseAuthenticationToken(userDetails, userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return WarehouseAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
